/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.oss.impl;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.exception.domain.MoonException;
import org.moon.framework.autoconfigure.oss.OssService;
import org.moon.framework.autoconfigure.oss.domain.MoonFile;
import org.moon.framework.autoconfigure.oss.props.OssProperties;
import org.moon.framework.autoconfigure.oss.utils.OssUtils;
import org.moon.framework.autoconfigure.utils.Func;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 七牛的oss
 * @author moon
 */
@Slf4j
public class QiniuOssProviderImpl implements OssService,OssProvider {

    private Auth auth;
    private OssProperties ossProperties;
    private UploadManager uploadManager;
    private BucketManager bucketManager;

    @Override
    public OssService builder(OssProperties ossProperties) {
        com.qiniu.storage.Configuration cfg = new com.qiniu.storage.Configuration(Zone.autoZone());
        this.ossProperties = ossProperties;
        this.auth = Auth.create(ossProperties.getAccessKey(), ossProperties.getSecretKey());
        this.uploadManager = new UploadManager(cfg);
        this. bucketManager = new BucketManager(auth, cfg);
        return this;
    }

    @Override
    public MoonFile putFile(MultipartFile file) {
        return putFile(file.getOriginalFilename(),file);
    }

    @Override
    public MoonFile putFile(String fileName, MultipartFile file) {
        String bucketName = OssUtils.getBucketName(ossProperties.getBucketName());
        try {
            if (!Func.contains(bucketManager.buckets(), bucketName)) {
                bucketManager.createBucket(bucketName, Zone.zone0().getRegion());
            }
            //获取上传凭证，普通上传
            fileName = OssUtils.getFileName(fileName);
            Response response = uploadManager.put(file.getInputStream(), fileName, auth.uploadToken(bucketName), null, null);
            int retry = 0;
            int retryCount = 5;
            while (response.needRetry() && retry < retryCount) {
                response = uploadManager.put(file.getInputStream(), fileName, auth.uploadToken(bucketName), null, null);
                retry++;
            }
            MoonFile moonFile = MoonFile.builder().originalName(fileName).name(fileName).domain(this.ossProperties.getEndpoint()).link(bucketName.concat("/").concat(fileName)).build();
            return moonFile;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public void removeFiles(List<String> fileNames) {
        fileNames.forEach(fileName -> removeFile(fileName));
    }

    @Override
    public void removeFile(String fileName) {
        try {
            bucketManager.delete(OssUtils.getBucketName(ossProperties.getBucketName()), fileName);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            throw new MoonException(MoonConstants.FAIL.getCode(),"删除文件失败",e);
        }
    }
}
